import UIKit

/// 页面B - 接收页面A的参数，并返回数据给Flutter
class PageBViewController: UIViewController {

    var params: [String: Any] = [:]

    private let paramsLabel = UILabel()
    private let returnButton = UIButton(type: .system)
    private let customDataTextField = UITextField()
    private let customDataLabel = UILabel()
    // 新增：数据流测试按钮
    private let startStreamButton = UIButton(type: .system)
    private let stopStreamButton = UIButton(type: .system)
    private let sendOnceButton = UIButton(type: .system)

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        displayParams()
    }

    private func setupUI() {
        // Use compatible background color for iOS versions before 13.0
        if #available(iOS 13.0, *) {
            view.backgroundColor = .systemBackground
        } else {
            view.backgroundColor = .white
        }
        title = "iOS原生页面B"

        // 设置自定义返回按钮 - 使用项目中的 ic_back 图片
        let backButton = UIButton(type: .custom)
        if let backImage = UIImage(named: "ic_back") {
            backButton.setImage(backImage, for: .normal)
        } else {
            if #available(iOS 13.0, *) {
                backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
            } else {
                // Fallback on earlier versions
            }
        }
        backButton.tintColor = .systemBlue
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)

        // 设置按钮大小
        backButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        backButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)

        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)

        // 参数显示标签
        paramsLabel.numberOfLines = 0
        paramsLabel.textAlignment = .center
        paramsLabel.font = .systemFont(ofSize: 14)
        paramsLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(paramsLabel)

        // 自定义数据标签
        customDataLabel.text = "自定义返回数据:"
        customDataLabel.font = .systemFont(ofSize: 16, weight: .medium)
        customDataLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(customDataLabel)

        // 自定义数据输入框
        customDataTextField.placeholder = "输入要返回给Flutter的数据"
        customDataTextField.borderStyle = .roundedRect
        customDataTextField.text = "这是页面B的自定义数据"
        customDataTextField.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(customDataTextField)

        // 返回按钮
        returnButton.setTitle("返回Flutter", for: .normal)
        if #available(iOS 13.0, *) {
            returnButton.backgroundColor = .systemGreen
        } else {
            returnButton.backgroundColor = UIColor(red: 52.0/255.0, green: 199.0/255.0, blue: 89.0/255.0, alpha: 1.0)
        }
        returnButton.setTitleColor(.white, for: .normal)
        returnButton.layer.cornerRadius = 8
        returnButton.addTarget(self, action: #selector(returnFlutterTapped), for: .touchUpInside)
        returnButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(returnButton)

        // 新增：数据流测试按钮配置
        configureTestButton(startStreamButton, title: "开始数据流", color: .systemBlue, action: #selector(startStreamTapped))
        configureTestButton(stopStreamButton, title: "停止数据流", color: .systemOrange, action: #selector(stopStreamTapped))
        configureTestButton(sendOnceButton, title: "手动发送一次", color: .systemPurple, action: #selector(sendOnceTapped))

        setupConstraints()
    }

    private func configureTestButton(_ button: UIButton, title: String, color: UIColor, action: Selector) {
        button.setTitle(title, for: .normal)
        if #available(iOS 13.0, *) {
            button.backgroundColor = color
        } else {
            button.backgroundColor = color
        }
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 8
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: action, for: .touchUpInside)
        view.addSubview(button)
    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([
            // 参数显示标签
            paramsLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30),
            paramsLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            paramsLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),

            // 自定义数据标签
            customDataLabel.topAnchor.constraint(equalTo: paramsLabel.bottomAnchor, constant: 40),
            customDataLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),

            // 自定义数据输入框
            customDataTextField.topAnchor.constraint(equalTo: customDataLabel.bottomAnchor, constant: 10),
            customDataTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            customDataTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            customDataTextField.heightAnchor.constraint(equalToConstant: 44),

            // 返回按钮
            returnButton.topAnchor.constraint(equalTo: customDataTextField.bottomAnchor, constant: 40),
            returnButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            returnButton.widthAnchor.constraint(equalToConstant: 200),
            returnButton.heightAnchor.constraint(equalToConstant: 44),

            // 开始数据流按钮
            startStreamButton.topAnchor.constraint(equalTo: returnButton.bottomAnchor, constant: 20),
            startStreamButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            startStreamButton.widthAnchor.constraint(equalToConstant: 200),
            startStreamButton.heightAnchor.constraint(equalToConstant: 44),

            // 停止数据流按钮
            stopStreamButton.topAnchor.constraint(equalTo: startStreamButton.bottomAnchor, constant: 12),
            stopStreamButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            stopStreamButton.widthAnchor.constraint(equalToConstant: 200),
            stopStreamButton.heightAnchor.constraint(equalToConstant: 44),

            // 手动发送一次按钮
            sendOnceButton.topAnchor.constraint(equalTo: stopStreamButton.bottomAnchor, constant: 12),
            sendOnceButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            sendOnceButton.widthAnchor.constraint(equalToConstant: 200),
            sendOnceButton.heightAnchor.constraint(equalToConstant: 44)
        ])
    }


    private func displayParams() {
        let paramsText = """
        接收到的参数：

        来源页面: \(params["fromPage"] ?? "未知")
        用户信息: \(params["userInfo"] ?? "无")
        时间戳: \(params["timestamp"] ?? "未知")
        消息: \(params["message"] ?? "无")
        """

        paramsLabel.text = paramsText
        print("📱 页面B显示参数: \(params)")
    }

    @objc private func backButtonTapped() {
        print("📱 页面B返回按钮被点击")



        navigationController?.popViewController(animated: true)
    }

    @objc private func returnFlutterTapped() {
        print("📱 页面B准备返回Flutter")

        // 准备返回给Flutter的数据
        let returnData: [String: Any] = [
            "page": "PageB",
            "action": "returnFlutter",
            "originalParams": params,
            "customData": customDataTextField.text ?? "无自定义数据",
            "timestamp": Date().timeIntervalSince1970,
            "message": "这是从页面B返回的数据"
        ]

        print("📱 页面B返回数据: \(returnData)")

        // 通过ChannelManager主动向Flutter发送数据
        ChannelManager.shared.sendDataToFlutter(data: returnData)

        // 关闭所有原生页面，回到Flutter
        dismiss(animated: true)
    }

    // MARK: - 数据流测试事件
    @objc private func startStreamTapped() {
        print("🚀 开始数据流")
        ChannelManager.shared.startDataStream()
    }

    @objc private func stopStreamTapped() {
        print("⏹️ 停止数据流")
        ChannelManager.shared.stopDataStream()
    }

    @objc private func sendOnceTapped() {
        print("📤 手动发送一次数据")
        let manual: [String: Any] = [
            "type": "manual",
            "timestamp": Date().timeIntervalSince1970,
            "data": [
                "note": "来自页面B的手动发送",
                "input": customDataTextField.text ?? ""
            ]
        ]

        ChannelManager.shared.sendManualData(manual)
    }
}
